package com.example.service.impl;

import com.example.entity.singerAndGame.Singer;
import com.example.mapper.SingerMapper;
import com.example.service.SingerService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Service
public class SingerServiceImpl implements SingerService {

    @Value("${files.upload.path}")
    String uploadPath;

    @Resource
    SingerMapper mapper;

    @Override
    public List<Singer> getSingerList() {
            return mapper.getSingerList();
    }

    @Override
    public Singer getSingerBySid(int sid) {
        return mapper.getSingerBySid(sid);
    }

    @Override
    public String addSinger(MultipartFile file, Singer singer) {
        if (file != null && !file.isEmpty()) {
            try {
                String fileName = System.currentTimeMillis() + file.getOriginalFilename();
                Path uploadFilePath = Paths.get(uploadPath, fileName);
                Files.createDirectories(uploadFilePath.getParent());
                file.transferTo(uploadFilePath.toFile());
                singer.setPic(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return "歌手新增出错，请检查输入信息是否有效";
            }
        }
        return mapper.addSinger(singer) > 0 ? null : "歌手新增失败，请稍后重试";
    }

    @Override
    public String updateSingerBySid(MultipartFile file, Singer singer) {
        if (file != null && !file.isEmpty()) {
            try {
                String fileName = System.currentTimeMillis() + file.getOriginalFilename();
                Path uploadFilePath = Paths.get(uploadPath, fileName);
                Files.createDirectories(uploadFilePath.getParent());
                file.transferTo(uploadFilePath.toFile());
                singer.setPic(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return "歌手修改出错，请检查输入信息是否有效";
            }
        }
        return mapper.updateSingerBySid(singer) > 0 ? null : "歌手修改失败，请稍后重试";
    }

    @Override
    public String deleteSingerBySid(int sid) {
        return mapper.deleteSingerBySid(sid) > 0 ? null : "歌手删除失败，请稍后重试";
    }
}
